#!/usr/bin/env python
"""tiny bridge board server"""""

from sys import *
import cgi
import cgitb
import random
cgitb.enable()

__version__ = "<b>0.1.0</b>/20100315";
__author__ = "towi@geocities.com";

###########################

def f(s):
    assert len(s) == 13+3
    ss = s.split(":")
    assert len(ss) == 4
    return ss

CARDS= set("AKDBT98765432")
assert len(CARDS) == 13
HSUIT = [
"<span style=color:#111;>&spades;</span>",
"<span style=color:#c00;>&hearts;</span>",
"<span style=color:#00c;>&diams;</span>",
"<span style=color:#0c0;>&clubs;</span>",
]

def ps(suite):
    r = 0
    if "A" in suite: r+=4
    if "K" in suite and len(suite)>=2: r+=3
    if "D" in suite and len(suite)>=3: r+=2
    if "B" in suite and len(suite)>=3: r+=1 # 3 is ok, almost
    if "T" in suite and len(suite)>=5 and r>=9: r+=1 # only in very strong suite
    if len(suite)>4: r += len(suite)-4
    return r
def p(hand):
    return sum(map(ps, hand))

def board(teiler, gefahr, n,e,s,w, title, link):
    d = f(n), f(e), f(s), f(w)
    for i in [0,1,2,3]:
        one_suite = set( d[0][i]+d[1][i]+d[2][i]+d[3][i] )
        assert CARDS == one_suite, "missing card? %s" % one_suite
    p_ns = p(d[0]) + p(d[2])
    p_ew = p(d[1]) + p(d[3])
    ns = " ".join( [HSUIT[i]+d[0][i]  for i in [0,1,2,3] ])
    es = " ".join( [HSUIT[i]+d[1][i]  for i in [0,1,2,3] ])
    ss = " ".join( [HSUIT[i]+d[2][i]  for i in [0,1,2,3] ])
    ws = " ".join( [HSUIT[i]+d[3][i]  for i in [0,1,2,3] ])
    res = ("{ N:'%s', E:'%s', S:'%s', W:'%s', title:'%s',link:'%s',t:'%s',g:'%s'}"
           ) % (ns,es,ss,ws, title, link, teiler, gefahr)
    return p_ns, p_ew, res

ALL_BOARDS = [
    board("N", "-", "B863:632:D832:D9", "T752:B8:AK:AB642", "K94:97:976:KT873", "AD:AKDT54:BT54:5",
        "BC Bi 2009-08-23:1",
        "http://www.bridge-club-bielefeld.de/sonstige/09_08_23_cpm_bdz_d1_bd1.html"),
]
BOARDS = {}
BOARDS['4pl'] = enumerate(ALL_BOARDS)
BOARDS['ns'] = filter(lambda b: b[1][0]>=18, enumerate(ALL_BOARDS))
BOARDS['ew']= filter(lambda b: b[1][1]>=18, enumerate(ALL_BOARDS))


###########################

if __name__ == "__main__":
    print "Content-Type: text/plain"
    print
    form = cgi.FieldStorage()
    s = form.getvalue("s", "ns")
    aid = form.getvalue("id")
    if aid:
        p_ns, p_ew, json = ALL_BOARDS[int(aid)]
        print json
    else:
        func = form.getvalue("f", "")
        if func in ["s", "sz", "size"]:
            print len(ALL_BOARDS)
        elif func in ["l", "ls", "list"]:
            for i,b in enumerate(ALL_BOARDS):
                p_ns, p_ew, cs = b
                print i, p_ns, p_ew, cs
        elif func in ["r","rid", "randid", "randomid"]:
            s = form.getvalue("s")
            bs = BOARDS[s]  if s else enumerate(ALL_BOARDS)
            b = random.choice(list(bs))
            print b[0]
        else:
            print "?id=N -- get a board with given N from SET"
            print "?f=size -- number of available boards"
            print "?f=randid[&s=SET] -- get a random id from SET"
            print "?f=list -- list all boards"
